<?php
namespace Api\Controller;

use Think\Controller;
use Think\Upload;
class ImageController extends Controller{
    
    /**
     * 上传图片
     * @param string $image_type 上传类型，默认微博
     * @param type $small 是否生成小图，默认false
     * @return array code：状态码；msg：状态信息；data：array-图片路径 
     */
    public function upload($image_type = 'weibo', $small = false){

        $config = C('UPLOAD_CONFIG');
        $upload = new Upload($config);
        $upload->savePath = '/'. $image_type .'/';
        $info = $upload->upload();
        if( !$info ){
            $data = array(
                'code'  => 0,
                'msg'   => $upload->getError(),
            );            
        }else{
            foreach ($info as $key => $value){
                $temp_path = '/Upload'. $value['savepath'] . $value['savename'];
                $save_path[] = $temp_path;
                if($small){
                    $this->saveSmallImage('.' .$temp_path);
                }
            }
            $data = array(
                'code'  => 1,
                'msg'   => '上传成功',
                'data'  => $save_path,
            );
        }
        return $data;
    }
    
    /**
     * 生成并保存小图
     * @param type 大图地址
     */
    public function saveSmallImage($file_path){
        $image = new \Think\Image();
        $image->open($file_path);
         //按照原图的比例生成一个最大为150*150的缩略图并保存为thumb. jpg
        $small = get_small_pic($file_path);
        $image->thumb(150, 150)->save($small);
    }
    
//    public function uploadImg($files, $type, $uid){
//        
//        $savepath = '/Upload/images' . $type . '/';
//        $time = time();
//        $conf=C('FILE_UPLOAD_CONFIG');
//        import('Org.Util.Alioss.Alioss');        
//        $Alioss=new \Alioss($conf);
//        foreach ($files as $key => $value){
//            if($value['size'] != 0){
//                $filetype = strtolower(strstr($value['name'], '.'));
//                if(!in_array($filetype, array('.jpg', '.jpeg', '.gif', '.png'))){
//                    return false;
//                }
//                $pic = $savepath . $uid . ($time++) . $filetype;
//                $picsize = $value['size'];            
//                $fh = fopen($value['tmp_name'], 'rb');
//                $result[] = $Alioss->uploadimg($pic,$fh,$picsize);
//                $pics[] = $pic;
//                fclose($fh);
//            }
//        }
//        return $pics;
//    }
}